from ftplib import FTP_TLS, FTP,error_perm
import socket,ssl

class ITLS(FTP_TLS):
    """FTP_TLS subclass that automatically wraps sockets in SSL to support implicit FTPS."""

    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        self._sock = None

    @property
    def sock(self):
        """Return the socket."""
        return self._sock

    @sock.setter
    def sock(self, value):
        """When modifying the socket, ensure that it is ssl wrapped."""
        if value is not None and not isinstance(value, ssl.SSLSocket):
            value = self.context.wrap_socket(value)
        self._sock = value

class ftp():
	def __init__(self,host, port,username, password):
		'''ITLS 隐式登录 '''
	    ftp = ITLS()
	    # ftp.set_debuglevel(2)
	    ftp.connect(host=host, port=port)
	    ftp.login(user=username, passwd=password)
	    ftp.prot_p()
	    self.ftp = ftp

	def mkdir(self,path):
	    '''创建path所有未创建的目录'''
	    for p in path.split('/'):
	        if p == '':
	            continue
	        try:
	            self.ftp.cwd(p)
	        except ftplib.error_perm:
	            self.ftp.mkd(p)
	            self.ftp.cwd(p)
	    self.ftp.cwd('/')

	def uploadfile(self, remotepath, localpath):
	    '''从本地上传文件到ftp'''
	    bufsize = 1024
	    fp = open(localpath, 'rb')
	    self.ftp.storbinary('STOR ' + remotepath, fp, bufsize)
	    self.ftp.set_debuglevel(0)
	    fp.close()

	def downloadfile(self, remotepath, localpath):
	    bufsize = 1024                
	    fp = open(localpath,'wb')     
	    self.ftp.retrbinary('RETR ' + remotepath, fp.write, bufsize) 
	    self.ftp.set_debuglevel(0)         
	    fp.close()